<?php

class MailList
{

	protected $confirmationUrl = 'maillist/confirm/';

	/**
	 * @var  array Website settings
	 **/
	protected $settings = array();

	/**
	 * @var  array  Class instances.
	 */
	protected static $instance;

	/**
	 * Returns an instance of Auth class by the given session id.
	 *
	 * @return  Auth
	 */
	public static function getInstance()
	{
		if (null == self::$instance) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Consrtuctor.
	 *
	 * @return  Auth
	 */
	public function __construct()
	{
		$this->init();
	}

	private function init()
	{
		$settings = Database::instance()->query('SELECT * FROM `settings`')->fetchAll();
		$values = array();
		foreach ($settings as $setting) {
			$this->settings[$setting['key']] = $values[$setting['key']] = $setting['value'];
		}
		unset($settings);
		$this->db = Database::instance();
		$this->model = Model::factory('mailList');
	}

	public function sendConfirmation($id = null, $email = null)
	{
		$subscriber = Model::factory('mailList')->getSubscriber($id, $email);
		$mail = new Mailer();
		$mail->to = $subscriber['email'];
		$mail->from = $this->settings['title'] . ' <' . $this->settings['email'] . '>';
		$mail->subject = 'Confirm your subscription from ' . $this->settings['title'];
		$message = '<h1>Confirm your subscription</h1><br>';
		$message .= '<p>Follow this link to confirm your subscription: ' . Html::anchor(Url::site($this->confirmationUrl . $subscriber['token'])) .'</p><br>';
		$mail->message(array('html' => new View('cli/message', array('message' => $message))));
		$mail->send();
	}

	public function subscribe($values, $confirmation = true)
	{
		$cnt = 0;
		Model_Table::instance('mailList')->keys['string'] = 'token';
		while (true === Model_Table::instance('mailList')->exists(($token = System::random('alphanuml', 6))) && $cnt < 3) {
			$cnt++;
		}
		$values['token'] = $token;
		$subscriberId = Model_Table::instance('mailList')->insert($values);
		if ((isset($values['confirmed']) ? !$values['confirmed'] : true) && $confirmation) {
			$this->sendConfirmation($subscriberId);
		}
	}
}
